package com.aura.springbook.controller;

import com.aura.springbook.common.R;
import com.aura.springbook.common.annotation.AdminRequired;
import com.aura.springbook.common.util.ResponseUtil;
import com.aura.springbook.common.exception.ResultCode;
import com.aura.springbook.model.Book;
import com.aura.springbook.model.BookCategory;
import com.aura.springbook.model.User;
import com.aura.springbook.service.AdminService;
import com.aura.springbook.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/admin")
@AdminRequired
@Tag(name = "管理员接口", description = "管理员相关操作接口")
public class AdminController {

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private AdminService adminService;

    /**
     * 创建图书分类
     */
    @PostMapping("/categories")
    @Operation(summary = "创建图书分类", description = "管理员创建新的图书分类")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功",
                    content = @Content(mediaType = "application/json",
                            schema = @Schema(implementation = R.class))),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<String> createCategory(@RequestBody BookCategory category) {
        logger.debug("收到创建图书分类请求, 分类名称: {}", category.getName());
        
        try {
            boolean result = adminService.createCategory(category);
            if (result) {
                logger.debug("创建图书分类成功, 分类ID: {}, 分类名称: {}", category.getId(), category.getName());
                return ResponseUtil.success("分类创建成功");
            } else {
                logger.warn("创建图书分类失败, 分类名称: {}", category.getName());
                return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, "分类创建失败");
            }
        } catch (Exception e) {
            logger.error("创建图书分类失败, 分类名称: {}, 错误信息: {}", category.getName(), e.getMessage(), e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 更新图书分类
     */
    @PutMapping("/categories/{id}")
    @Operation(summary = "更新图书分类", description = "管理员更新图书分类信息")
    @Parameters({
            @Parameter(name = "id", description = "分类ID", required = true),
            @Parameter(name = "category", description = "分类信息", required = true)
    })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<String> updateCategory(@PathVariable Long id, @RequestBody BookCategory category) {
        logger.debug("收到更新图书分类请求, 分类ID: {}", id);
        
        category.setId(id);
        try {
            boolean result = adminService.updateCategory(category);
            if (result) {
                logger.debug("更新图书分类成功, 分类ID: {}", id);
                return ResponseUtil.success("分类更新成功");
            } else {
                logger.warn("更新图书分类失败, 分类ID: {}", id);
                return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, "分类更新失败");
            }
        } catch (Exception e) {
            logger.error("更新图书分类失败, 分类ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 删除图书分类
     */
    @DeleteMapping("/categories/{id}")
    @Operation(summary = "删除图书分类", description = "管理员删除图书分类")
    @Parameter(name = "id", description = "分类ID", required = true)
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<String> deleteCategory(@PathVariable Long id) {
        logger.debug("收到删除图书分类请求, 分类ID: {}", id);
        
        try {
            boolean result = adminService.deleteCategory(id);
            if (result) {
                logger.debug("删除图书分类成功, 分类ID: {}", id);
                return ResponseUtil.success("分类删除成功");
            } else {
                logger.warn("删除图书分类失败, 分类ID: {}, 可能该分类下还有图书", id);
                return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, "分类删除失败，可能该分类下还有图书");
            }
        } catch (Exception e) {
            logger.error("删除图书分类失败, 分类ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 获取所有图书分类
     */
    @GetMapping("/categories")
    @Operation(summary = "获取所有图书分类", description = "管理员获取所有图书分类列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<List<BookCategory>> getAllCategories() {
        logger.debug("收到获取所有图书分类请求");
        
        List<BookCategory> categories = adminService.getAllCategories();
        logger.debug("获取所有图书分类成功, 总数: {}", categories.size());
        return ResponseUtil.success(categories);
    }

    /**
     * 创建图书
     */
    @PostMapping("/books")
    @Operation(summary = "创建图书", description = "管理员创建新的图书")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<String> createBook(@RequestBody Book book) {
        logger.debug("收到创建图书请求, 图书标题: {}", book.getTitle());
        
        try {
            boolean result = adminService.createBook(book);
            if (result) {
                logger.debug("创建图书成功, 图书ID: {}, 图书标题: {}", book.getId(), book.getTitle());
                return ResponseUtil.success("图书创建成功");
            } else {
                logger.warn("创建图书失败, 图书标题: {}", book.getTitle());
                return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, "图书创建失败");
            }
        } catch (Exception e) {
            logger.error("创建图书失败, 图书标题: {}, 错误信息: {}", book.getTitle(), e.getMessage(), e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 更新图书
     */
    @PutMapping("/books/{id}")
    @Operation(summary = "更新图书", description = "管理员更新图书信息")
    @Parameters({
            @Parameter(name = "id", description = "图书ID", required = true),
            @Parameter(name = "book", description = "图书信息", required = true)
    })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<String> updateBook(@PathVariable Long id, @RequestBody Book book) {
        logger.debug("收到更新图书请求, 图书ID: {}", id);
        
        book.setId(id);
        try {
            boolean result = adminService.updateBook(book);
            if (result) {
                logger.debug("更新图书成功, 图书ID: {}", id);
                return ResponseUtil.success("图书更新成功");
            } else {
                logger.warn("更新图书失败, 图书ID: {}", id);
                return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, "图书更新失败");
            }
        } catch (Exception e) {
            logger.error("更新图书失败, 图书ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 删除图书
     */
    @DeleteMapping("/books/{id}")
    @Operation(summary = "删除图书", description = "管理员删除图书")
    @Parameter(name = "id", description = "图书ID", required = true)
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<String> deleteBook(@PathVariable Long id) {
        logger.debug("收到删除图书请求, 图书ID: {}", id);
        
        try {
            boolean result = adminService.deleteBook(id);
            if (result) {
                logger.debug("删除图书成功, 图书ID: {}", id);
                return ResponseUtil.success("图书删除成功");
            } else {
                logger.warn("删除图书失败, 图书ID: {}, 可能还有未归还的借阅记录", id);
                return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, "图书删除失败，可能还有未归还的借阅记录");
            }
        } catch (Exception e) {
            logger.error("删除图书失败, 图书ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 更新图书库存
     */
    @PutMapping("/books/{id}/stock")
    @Operation(summary = "更新图书库存", description = "管理员更新图书库存数量")
    @Parameters({
            @Parameter(name = "id", description = "图书ID", required = true),
            @Parameter(name = "stock", description = "库存数量", required = true)
    })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<String> updateBookStock(@PathVariable Long id, @RequestParam int stock) {
        logger.debug("收到更新图书库存请求, 图书ID: {}, 新库存: {}", id, stock);
        
        if (stock < 0) {
            logger.warn("更新图书库存失败, 库存不能为负数, 图书ID: {}, 库存: {}", id, stock);
            return ResponseUtil.paramError("库存不能为负数");
        }

        try {
            boolean result = adminService.updateBookStock(id, stock);
            if (result) {
                logger.debug("更新图书库存成功, 图书ID: {}, 新库存: {}", id, stock);
                return ResponseUtil.success("库存更新成功");
            } else {
                logger.warn("更新图书库存失败, 图书ID: {}", id);
                return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, "库存更新失败");
            }
        } catch (Exception e) {
            logger.error("更新图书库存失败, 图书ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 获取所有用户
     */
    @GetMapping("/users")
    @Operation(summary = "获取所有用户", description = "管理员获取所有用户列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<List<User>> getAllUsers() {
        logger.debug("收到获取所有用户请求");
        
        List<User> users = adminService.getAllUsers();
        logger.debug("获取所有用户成功, 总数: {}", users.size());
        return ResponseUtil.success(users);
    }

    /**
     * 更新用户角色
     */
    @PutMapping("/users/{id}/role")
    @Operation(summary = "更新用户角色", description = "管理员更新用户角色（普通用户/管理员）")
    @Parameters({
            @Parameter(name = "id", description = "用户ID", required = true),
            @Parameter(name = "role", description = "用户角色（USER/ADMIN）", required = true)
    })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<String> updateUserRole(@PathVariable Long id, @RequestParam String role) {
        logger.debug("收到更新用户角色请求, 用户ID: {}, 新角色: {}", id, role);
        
        try {
            boolean result = adminService.updateUserRole(id, role);
            if (result) {
                logger.debug("更新用户角色成功, 用户ID: {}, 新角色: {}", id, role);
                return ResponseUtil.success("用户角色更新成功");
            } else {
                logger.warn("更新用户角色失败, 用户ID: {}", id);
                return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, "用户角色更新失败");
            }
        } catch (Exception e) {
            logger.error("更新用户角色失败, 用户ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR, e.getMessage());
        }
    }
}